package com.googlecode.imule.redundant;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.util.Scanner;


/**
 * The ListenerThread monitors a the command line for input coming in.
 * 
 * TODO: Remove from code base. Purely here for test purposes
 * 
 * @author Graeme Stevenson
 * @author Graham Williamson
 * @author Neil Cowzer
 */
public class ListenerThreads extends Thread {
	/** Indicates if this thread should shut down */
	private boolean shutdown;
	
	private DiscoveryService owner;
	
	private Scanner reader;
	
	/**
	 * Creates a new listener thread to monitor a socket.
	 */
	public ListenerThreads(DiscoveryService owner) {
		this.shutdown = false;
		this.owner = owner;

		// set up a scanner to read from the input in
		reader = new Scanner(System.in);
	}
	
	/**
	 * The run method monitors the socket for incoming data, printing whatever
	 * it gets...
	 */
	public void run() {
		while (!shouldShutdown()) {
			try {
				String status = reader.nextLine();
				owner.setStatus(status);
			} catch (Exception e) {
				System.out.println("error");
				e.printStackTrace();
				break; // terminate thread
			}
		}
	}

	/**
	 * Check if we should shutdown the listener thread.
	 * @return true if we should shutdown; false otherwise.
	 */
	public synchronized boolean shouldShutdown() {
		return shutdown;
	}
	
	/**
	 * Notify this listener thread that it should shutdown.
	 */
	public synchronized void shutdown() {
		shutdown = true;
	}

}
